<?php

namespace Worker\Logic;

use \Common\Logic\BaseLogic;

class UserLogic extends BaseLogic
{
    private $userModel;
    
    const USER_COOKIE_NAME = 'worker_user_info';
    const CRYPT_KEY = 'FmL2UrsftJeF7LecaBh0V7UZHiQ7VsDN';

    public function __construct()
    {
        parent::__construct();
        $this->userModel = D('User');
    }

    /**
     * 编辑用户,暂时只支持改密码
     *
     * @param [type] $userId
     * @param [type] $data
     * @return void
     */
    public function editUser($userId, $data)
    {
        if (empty($userId)) {
            return static::$res->err("userId不能为空");
        }
        $userWhere = array(
            "id" => $userId,
            "user_state" => 1,
            "is_worker"=>1
        );

        $userInfo = $this->userModel->where($userWhere)->find();
        if (empty($userInfo)) {
            return static::$res->err("推手信息异常");
        }

        $upData = array();
        if (!empty($data["pwd"])) {
            if ($data["pwd"] != $data["repwd"]) {
                return static::$res->err("两次密码不一致");
            }

            if ($this->md5Password($data['oldpwd']) != $userInfo["password"]) {
                return static::$res->err("原密码错误");
            }

            $upData["password"] = $this->md5Password($data['pwd']);
            if ($upData["password"] == $this->md5Password($data['oldpwd'])) {
                return static::$res->err("密码没有改变");
            }
        }

        if (empty($upData)) {
            return static::$res->err("没有任何改变");
        }

        $count = $this->userModel->where($userWhere)->save($upData);
        if (empty($count)) {
            return static::$res->err("数据库异常,编辑失败");
        }

        return static::$res->suc("成功");
    }


    /**
     * 获取用户登录信息
     * @return mixed
     */
    public function getUserInfo()
    {
        $userInfoRes = $this->getUserInfoByCookie();
        if (!static::$res->isSuc($userInfoRes)) {
            return static::$res->err("用户未登陆");
        }
        $userInfo = $userInfoRes['Result'];

        if ($userInfo['expire'] < time()) {
            return static::$res->err("登陆信息已过期");
        }

        $id = $userInfo['id'];

        $userWhere = array(
            "id" => $id,
            "user_state" => 1,
            "is_worker"=>1
        );

        if ($this->userModel->where($userWhere)->count() < 1) {
            return static::$res->err("登陆信息异常");
        }

        $userInfo['expire'] = strtotime("+1 day");

        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 登陆账号
     * @param $phone
     * @param $password
     * @return mixed
     */
    public function login($phone, $password)
    {
        if (empty($phone)) {
            return static::$res->err("登陆手机不能为空");
        }
        if (!validate($phone, 'mobile')) {
            return static::$res->err("手机号格式错误");
        }
        if (empty($password)) {
            return static::$res->err("密码不能为空");
        } else {
            $password = $this->md5Password($password);
        }

        $where = array(
            "phone" => $phone,
            "password" => $password,
            "user_state" => 1,
            "is_worker"=>1
        );

        $userInfo = $this->userModel->where($where)->find();
        if (empty($userInfo)) {
            return static::$res->err("账号或密码错误");
        }

        $userInfo['expire'] = strtotime("+1 day");
        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        cookie(static::USER_COOKIE_NAME, null);
        return static::$res->suc('成功');
    }

    /**
     * 通过cookie获取登录信息
     * @return mixed
     */
    private function getUserInfoByCookie()
    {
        $cookieStr = cookie(static::USER_COOKIE_NAME);
        if (empty($cookieStr)) {
            return static::$res->err("登录信息不存在");
        }
        $userInfoJson = \Think\Crypt::decrypt($cookieStr, static::CRYPT_KEY);
        $userInfo = json_decode($userInfoJson, true);
        if (empty($userInfo)) {
            return static::$res->err("登录信息失效");
        }

        return static::$res->suc('成功', $userInfo);
    }


    /**
     * 将用户信息写入到cookie
     * @param type $userInfo
     */
    private function setUserInfoToCookie($userInfo)
    {
        $userInfoJson = json_encode($userInfo);
        $val = \Think\Crypt::encrypt($userInfoJson, static::CRYPT_KEY);
        cookie(static::USER_COOKIE_NAME, $val);
    }

    /**
     * 加密密码
     * @param $password
     * @return string
     */
    private function md5Password($password)
    {
        $val = md5($password);
        return $val;
    }
}
